package com.ayitubie.refuelweb.service;

import com.alibaba.fastjson.JSON;
import com.ayitubie.refuelweb.config.jedis.JedisService;
import com.ayitubie.refuelweb.entity.User;
import com.ayitubie.refuelweb.mapper.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.apache.rocketmq.common.message.Message;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServ {

    @Autowired
    UserMapper userMapper;

    @Autowired
    JedisService jedisService;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    DefaultMQProducer defaultMQProducer;

    @Autowired
    RedissonClient redissonClient;


    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    public int insertUser(User user) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        int count = userMapper.insertUser(user);
        try {
            Message sendMsg = new Message("TestTopic", "TestTag", JSON.toJSONBytes(user));
            sendMsg.setDelayTimeLevel(3); //10秒后发送
            defaultMQProducer.sendOneway(sendMsg);
        } catch (Exception e) {
            log.error("RocketMq_InsertUser:{}", e.getMessage());
            Thread.currentThread().interrupt();
        }
        return count;
    }

    public String login(String userName, String password) {
        User user = userMapper.login(userName, password);
        if (user != null) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            int userId = user.getUserId();
            String token = uuid + userId;
            jedisService.set("loginUser" + userId, token);
            jedisService.expire("loginUser" + userId, 60 * 60);
            //登录设置一个分布式限流信号量，/test/TimeLimit测试下
            RSemaphore semaphore = redissonClient.getSemaphore("TimeLimit");
            semaphore.trySetPermits(10000);
            jedisService.expire("TimeLimit", 24 * 60 * 60);
            return token;
        }
        return "";
    }

    public User getUserByUserId(String userId) {
        return userMapper.getUserByUserId(userId);
    }

    public int checkUserExist(String userName) {
        return userMapper.checkUserExist(userName);
    }
}
